package com.neu.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.neu.po.Food;
import com.neu.po.User;
import com.neu.util.DBUtil;

public class FoodDaolmpl implements FoodDao {

	@Override
	public int delete(int fid) throws ClassNotFoundException, SQLException {
		String sql = "delete from food where fid = ?";
		return 	DBUtil.executeUpdate(sql, fid);
	}

	@Override
	public List<Food> getAll() throws ClassNotFoundException, SQLException {
		String sql = "select * from food";
		Connection connection = DBUtil.getConnection();
		ResultSet rs = DBUtil.executeQuery(connection, sql);
		
		Food food = null;
		List<Food> list =new ArrayList<Food>();
		
		int fid;
		String fname;
		String feg;
		int price;
		
		while(rs.next()) {
			fid = rs.getInt("fid");
			fname = rs.getString("fname");
			feg = rs.getString("feg");
			price = rs.getInt("price");
			
			food = new Food(fid, fname, feg, price);
			list.add(food);
		}
		
		return list;
	}

	@Override
	public int insert(Food food) throws ClassNotFoundException, SQLException {
		String sql = "insert into food values (null,?,?,?)";
		Connection connection = DBUtil.getConnection();
	    int n = DBUtil.executeUpdate(sql,food.getFname(),food.getFeg(),food.getPrice());
	    DBUtil.closeConnection(connection);
		return n;
	}

	@Override
	public int update(Food food) throws ClassNotFoundException, SQLException {
		String sql = "update food set fname = ? , feg = ? , price = ? where fid = ?";
		int n = DBUtil.executeUpdate(sql,food.getFname(),food.getFeg(),food.getPrice(),food.getFid() );
		
		return n;
	}

	@Override
	public Food getById(int fid) throws ClassNotFoundException, SQLException {
		String sql = "select * from food where fid =? ";
		Connection connection = DBUtil.getConnection();
		ResultSet rs = DBUtil.executeQuery(connection, sql, fid);
		Food food = null;
		
		String fname;
		String feg;
		int price;
		
		if(rs.next()) {
			fname = rs.getString("fname");
			feg = rs.getString("feg");
			price = rs.getInt("price");
			food = new Food(fid, fname, feg, price);
		}
		DBUtil.closeConnection(connection);
		
		return food;
	}

}
